<?php
/**
 * Created by PhpStorm.
 * User: guanfangge
 * Date: 4/26/22
 * Time: 10:51 AM
 */
namespace App\HttpController;

use EasySwoole\EasySwoole\Trigger;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Component\Di;
use EasySwoole\Jwt\Jwt;
use EasySwoole\HttpAnnotation\AnnotationController;
use EasySwoole\HttpAnnotation\AnnotationTag\Param;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;


abstract class Base extends Controller
{

    public function onException(\Throwable $throwable): void
    {
        if($throwable instanceof ParamValidateError){
            $this->response()->withHeader('Content-type','text/html;charset=utf-8');
            $this->writeJson(0,"字段【{$throwable->getValidate()->getError()->getField()}】校验错误");
        }else{
            Trigger::getInstance()->throwable($throwable);
        }
    }
    /**
     * 接口请求量
     *
     * CreateTime: 2020/8/19 12:37 上午
     */
    public function requestTotal()
    {
        $this->response()->write('请求数+1' . PHP_EOL);

        // 还可以 return，但不要两个方法互相调用，会导致死循环
    }

    /**
     * gc 方法将在执行完 afterAction 方法之后自动调用，可自行覆盖实现其他的 gc 回收逻辑
     *
     * CreateTime: 2020/8/19 12:52 上午
     */
    public function gc()
    {
        parent::gc(); // TODO: Change the autogenerated stub
    }

    /**
     * 当控制器方法执行结束之后将调用该方法，可自行覆盖该方法实现数据回收等逻辑
     *
     * @param string|null $actionName
     * CreateTime: 2020/8/19 12:51 上午
     */
    public function afterAction(?string $actionName): void
    {
        parent::afterAction($actionName); // TODO: Change the autogenerated stub
    }

    /**
     * 当请求方法未找到时，自动调用该方法，可自行覆盖该方法实现自己的逻辑
     *
     * @param string|null $action
     * CreateTime: 2020/8/19 12:51 上午
     */
    public function actionNotFound(?string $action)
    {
        parent::actionNotFound($action); // TODO: Change the autogenerated stub
    }

    /**
     * 所有控制器请求都会先经过该方法，如果此方法返回 false 则请求不继续往下执行，可用于权限验证
     *
     * @param string|null $action
     * @return bool|null
     * CreateTime: 2020/8/19 12:52 上午
     */
    public function onRequest(?string $action): ?bool
    {
        $token = $this->request()->getHeader('token');
        if(empty($token)){
            $this->writeJson(401, null, 'token为空');
            return false;
        }
        // 对 cookie 进行判断，比如在数据库或者是 redis 缓存中，存在该 cookie 信息，说明用户登录成功
        try {
            $jwtObject = Jwt::getInstance()->decode($token[0]);
            $status = $jwtObject->getStatus();
            if($status!=1){
                $this->writeJson(401, null, 'token不正确');
                return false;
            }
            $this->user = json_decode($jwtObject->getData(),true);
            return true;
        } catch (\EasySwoole\Jwt\Exception $e) {
            return $this->writeJson(0,$e->getMessage());
        }
    }
}
